#!/bin/bash
#
# Copyright (C) 2017 ~ 2018 Deepin Technology Co., Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# Create swap file if no swap partition is set.

SWAP_FILE_REQUIRED=$(installer_get "DI_SWAP_FILE_REQUIRED")
SWAP_FILE_PATH=$(installer_get "partition_swap_file_path")
SWAP_FILE_SIZE=$(installer_get "partition_swap_file_size")

[ -z "${SWAP_FILE_PATH}" ] && error "SWAP_FILE_PATH is empty"

SWAP_FILE_PATH="/target${SWAP_FILE_PATH}"

if [ x"${SWAP_FILE_REQUIRED}" = "xtrue" ]; then
  # A swap file is required.
  if [[ "$(df --output=fstype ${SWAP_FILE_PATH%/*})" =~ $'\n'(ext4|xfs)$ ]]
  then
    fallocate -l "${SWAP_FILE_SIZE}MiB" "${SWAP_FILE_PATH}"
  else
    dd if=/dev/zero of="${SWAP_FILE_PATH}" count="${SWAP_FILE_SIZE}" bs=1M
  fi || error "Failed to create swap file: ${SWAP_FILE_PATH}"

  chmod 0600 "${SWAP_FILE_PATH}" || \
    warn "Failed to change permission of ${SWAP_FILE_PATH}"
  mkswap "${SWAP_FILE_PATH}" || error "mkswap ${SWAP_FILE_PATH} failed"
fi
